package server

import (
	"bytes"
	"devops-tools/config"
	"devops-tools/util"
	"encoding/json"
	"github.com/sirupsen/logrus"
	"net/http"
	"strings"
	"time"
)

//执行webhook
func WebHook(noticeMsg string) {
	logrus.Println("执行webhook")
	if config.GetConfig().Alarm.Webhook == "" {
		logrus.Println("未配置webhook")
		return;
	}
	msg := strings.Replace(noticeMsg, "{ip}", util.GetHostIp(), 1)
	msg = strings.Replace(msg, "{date_time}", time.Now().Format("2006-01-02 15:04:05"), 1)
	data := map[string]interface{}{"msg": msg, "appid": config.GetConfig().Appid}
	jsonStr, _ := json.Marshal(data)
	logrus.Println("请求参数", string(jsonStr))
	request, e := http.NewRequest("POST", config.GetConfig().Alarm.Webhook, bytes.NewBuffer(jsonStr))
	if e != nil {
		logrus.Println("请求webhook失败")
		return
	}
	request.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	response, e := client.Do(request)
	if e != nil {
		logrus.Println("请求webhook失败:", e)
		return
	}
	defer response.Body.Close()
	logrus.Print("响应结果:", string(response.Status))
}
